import { DatePicker as AntdDatePicker } from '@sei/suid-mobile';
import dayjs from 'dayjs';
import formatPlugin from 'dayjs/plugin/advancedFormat';
import updateLocalePlugin from 'dayjs/plugin/updateLocale';
import weekOfYearPlugin from 'dayjs/plugin/weekOfYear';
import { omit } from 'lodash-es';
import React, { useImperativeHandle, useRef } from 'react';
import { getFormat } from '../utils';
import './index.less';

dayjs.extend(updateLocalePlugin);
dayjs.extend(formatPlugin);
dayjs.extend(weekOfYearPlugin);

dayjs.updateLocale('en', {
  weekStart: 1,
});

export default (props: any) => {
  const {
    value,
    onChange,
    precision = 'day',
    placeholder = '请选择日期',
    format,
    ...restProps
  } = omit(props, ['addons', 'schema']);

  const pickerRef: any = useRef(null);

  // 使用useImperativeHandle暴露方法给外部
  useImperativeHandle(props.addons.fieldRef, () => ({
    ...pickerRef?.current,
  }));

  const dateFormat = format || getFormat(precision);

  const handleChange = (dateString: string, date: Date) => {
    onChange(dateString);
  };

  // 当精度为秒时，添加额外的样式确保显示完整
  const isSecondPrecision = precision === 'second';

  return (
      <AntdDatePicker
        className={isSecondPrecision ? 'date-picker-wrapper' : ''}
        ref={pickerRef}
        value={value}
        onConfirm={handleChange}
        precision={precision}
        {...restProps}
      >
        {(_, date) => (
          <div>
            {date && value ? (
              dayjs(date).format(dateFormat)
            ) : (
              <span style={{ color: '#ccc' }}>{placeholder}</span>
            )}
          </div>
        )}
      </AntdDatePicker>
  );
};
